package com.block.api.controller.expose;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.alibaba.fastjson.JSON;
import com.block.channel.service.IChannelBaseInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.ChannelBaseInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 短链接
 */
@Controller
@RequestMapping("")
public class ShortLinkController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IChannelBaseInfoService channelBaseInfoService;

    /**
     * 渠道访问，获取落地页接口
     */
    @RequestMapping(value = "{channelCode}", method = {RequestMethod.GET, RequestMethod.POST})
    public String channelInfo(HttpServletRequest request,
                          HttpServletResponse response,
                          ModelMap modelMap,
                          @PathVariable(value = "channelCode", required = false) String channelCode
    ) throws Exception {

        // 查询渠道信息缓存
        ChannelBaseInfo channelInfo = channelCommonService.getBaseInfoByCode(channelCode);
        String result = this.canVisit(request, channelInfo);
        if (StrUtil.isNotEmpty(result)){
            modelMap.put("message", result);
            return "error";
        }

        try {

            // 2.根据渠道信息，获取相应的下载页
            String viewUrl = channelBaseInfoService.channelUvHandle(channelInfo, request);

            if (StrUtil.isEmpty(viewUrl)){
                modelMap.put("message", "渠道地址不可用，联系管理员");
                return "error";
            }

            try {

                Map<String, String[]> parameterMap = request.getParameterMap();
                for (String key : parameterMap.keySet()) {
                    String parameter = request.getParameter(key);
                    viewUrl = viewUrl + "&"+key+"="+parameter;
                }
            }catch (Exception exception){
                exception.printStackTrace();
            }

            // 正常返回页面地址信息
            return "redirect:" + viewUrl;
        }catch (Exception exception){
            exception.printStackTrace();
        }

        modelMap.put("message", "获取渠道地址失败");
        return "error";
    }

    public String canVisit(HttpServletRequest request, ChannelBaseInfo channelBaseInfo){
        try {
            if (ObjectUtil.isEmpty(channelBaseInfo)){
                // 渠道信息为空，不可以通过渠道信息进行访问
                return "渠道信息为空，不可访问";
            }

            if (ObjectUtil.equal(channelBaseInfo.getStatus(), Integer.valueOf(0)) ||
                    ObjectUtil.equal(channelBaseInfo.getDelFlag(), Integer.valueOf(1))){
                // 渠道下架或者删除，不可以进行访问
                return "当前渠道已关闭";
            }

            String userAgentStr = request.getHeader("User-Agent");
            UserAgent userAgent = UserAgentUtil.parse(userAgentStr);

            // 来源屏蔽
            List<String> browserNameList = JSON.parseArray(channelBaseInfo.getNotVisitBrowser(), String.class);
            String browserName = userAgent.getBrowser().getName();
            if (CollUtil.isNotEmpty(browserNameList) &&
                    browserNameList.contains(browserName)){
                return "当前应用不支持访问";
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }
        return "";
    }
}
